package org.testfire.realm.util;

import javax.el.ValueExpression;
import javax.el.ELContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.transaction.UserTransaction;
import org.testfire.realm.control.testfire.TestFireDBAO;

/**
 * Created by IntelliJ IDEA.
 * User: granum
 * Date: Sep 3, 2007
 * Time: 8:24:05 PM
 *
 */
public class EntityUtil
{




    public static EntityManager getEntityManager( String persistenceUnitName, FlushModeType flushType )
    {
        try
        {
            flushType = flushType == null ? FlushModeType.AUTO : flushType;
            // obtain the initial JNDI context
            EntityManagerFactory emf = null;
            Context initCtx = new InitialContext();
            // perform JNDI lookup to obtain entity manager factory

            emf = (EntityManagerFactory)initCtx
                .lookup( String.format( "java:comp/env/persistence/%1$s", persistenceUnitName ) );
            EntityManager em = emf.createEntityManager();
            em.setFlushMode( flushType );
            return em;
        }
        catch ( NamingException e )
        {
            throw new IllegalStateException( e );
        }

    }

    public static UserTransaction getUserTransaction()
    {
        Context initCtx = null;
        try
        {
            initCtx = new InitialContext();
            return (UserTransaction)initCtx.lookup( "java:comp/UserTransaction" );
        }
        catch ( NamingException e )
        {
            throw new IllegalStateException( e );
        }

    }
}
